package com.just.springjpa.dao;

import com.just.springjpa.domain.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import javax.transaction.Transactional;
import java.util.List;

public interface PersonRepository extends JpaRepository<Person,Long> {
    //使用方法名查询,返回列表
    List<Person> findByAddress(String address);
    //使用方法名查询，返回单个对象
    Person findByNameAndAddress(String name,String address);
    //使用query查询，参数按照名称绑定
    @Query(value = "select p from Person p where p.name=:name and p.address=:address")
    Person withNameAndAddressQuery(@Param("name")String name,@Param("address")String address);
    //使用NamedQuery查询，在实体类中做了定义
    List<Person> withNameAndAddressNamedQuery(String name,String address);

    //自定义查询
    @Query(value = "select * from person where name=?1 and age>18",nativeQuery = true)
    List<Person> findByMyQuery(String name);

    //更新操作(更新，删除的操作必须有事务，这个事务可以在这里写，也可以在service里写)
    @Transactional
    @Modifying
    @Query(value = "update Person set age=?2 where id=?1")
    int updatePersonAge(Long id,int age);

    @Transactional
    //删除操作
    int deleteByAge(int age);
}
